
/*
 *	
 */
 
var socket = new WebSocket('ws://127.0.0.1:1337/');// change the IP address to your websocket server
var stunServer = "stun.l.google.com:19302";

var sourcevid = document.getElementById('sourcevid');
var remotevid = document.getElementById('remotevid');

var localStream = null;
var remoteStream;

var peerConn = null;
var started = false;

var isRTCPeerConnection = true;
var mediaConstraints = {
	'mandatory': {
		'OfferToReceiveAudio':true, 
		'OfferToReceiveVideo':true }
	};
							
var logg = function(s) { console.log(s); };
 
//for text chat
var chatInput;
var chatArea;
var chatNick;
var chatFrame;
var author;
var to;
var tos = new Array();	// group chat
//Lay ten ng dung.

chatNick = document.getElementById("userName");

$('.inputField').keydown(function(event) { 
	
	to = $(this).parent().parent().find('h3').html();

	// Get each user who will recieve this message (When chat group)
	/*
	var i = 0;
	while (to.indexOf('&') != -1) {
		var j = to.indexOf('&') - 1;
		tos[i] = to.substring(i, j);
		to = to.substring(j + 1, to.length);
		i++;
	}
	alert(tos);
	return;*/
});

 //Khoi tao ket noi giua client.
function createPeerConnection() {
	try {
		logg("Creating peer connection");
		var servers = [];
		servers.push({'url':'stun:' + stunServer});
		var pc_config = {'iceServers' : servers};
		
		peerConn = new webkitRTCPeerConnection(pc_config);
		peerConn.onicecandidate = onIceCandidate;
	} catch (e) {
		try {
			peerConn = new RTCPeerConnection('STUN ' + stunServer, onIceCandidate00);
			isRTCPeerConnection = false;
		} catch (e) {
			logg("Failed to create PeerConnection, exception: " + e.message);
		}
	}

	peerConn.onaddstream = onRemoteStreamAdded;
	peerConn.onremovestream = onRemoteStreamRemoved;
}
 
// when remote adds a stream, hand it on to the local video element
function onRemoteStreamAdded(event) {
	logg("Added remote stream");
	remotevid.src = window.webkitURL.createObjectURL(event.stream);
}
 
function waitForRemoteVideo() {
	if (remoteStream.videoTracks.length === 0 || remotevid.currentTime > 0) {
		transitionToActive();
	} else {
		setTimeout(waitForRemoteVideo, 100);
	}
}

function transitionToActive() {
	remotevid.style.opacity = 1;
	card.style.webkitTransform = "rotateY(180deg)";
	setTimeout(function() { sourcevid.src = ""; }, 500);
	setStatus("<input type=\"button\" id=\"hangup\" value=\"Hang up\" onclick=\"onHangup()\" />");
}

// when remote removes a stream, remove it from the local video element
function onRemoteStreamRemoved(event) {
	logg("Remove remote stream");
	remotevid.src = "";
}
 
function onIceCandidate(event) {
	if (event.candidate) {
		sendMessage({
			type: 'candidate',
			label: event.candidate.sdpMLineIndex,
			id: event.candidate.sdpMid,
			candidate: event.candidate.candidate
		});
	} else {
		logg("End of candidates.");
	}
}
 
function onIceCandidate00(candidate, moreToFollow) {
	if (candidate) {
		sendMessage({type: 'candidate', label: candidate.label, candidate: candidate.toSdp()});
	}
	if (!moreToFollow) {
		logg("End of candidates.");
	}
}
 
// start the connection upon user request
function connect() {
	if (!started && localStream) {	//Neu nhu chua bat dau ket noi va da mo Webcam cua may
		//Hien thi hinh anh connecting
		//document.getElementById('anim').style.visibility='visible';
		console.log("Creating PeerConnection.");
		
		//Tao ket noi
		createPeerConnection();
		logg('Adding local stream...');
		
		
		peerConn.addStream(localStream);
		started = true;
		logg("isRTCPeerConnection: " + isRTCPeerConnection);
 
		//create offer
		if (isRTCPeerConnection) {
			peerConn.createOffer(setLocalAndSendMessage, null, mediaConstraints);
		} else {
			var offer = peerConn.createOffer(mediaConstraints);
			peerConn.setLocalDescription(peerConn.SDP_OFFER, offer);
			sendMessage({type: 'offer', sdp: offer.toSdp()});
			peerConn.startIce();
		}
	 
	} else {
		alert("Local stream not running yet.");
	}
}
 
// accept connection request
socket.addEventListener("message", onMessage, false);

function onMessage(evt) {
	logg("RECEIVED: " + evt.data);
	if (isRTCPeerConnection)
		processSignalingMessage(evt.data);
	else
		processSignalingMessage00(evt.data);
}
 
function processSignalingMessage(message) {
	var msg = JSON.parse(message);
 
	if (msg.type === 'offer') { 
		if (!started && localStream) {
		
			createPeerConnection();
			logg('Adding local stream...');
			peerConn.addStream(localStream);
			started = true;
			logg("isRTCPeerConnection: " + isRTCPeerConnection);
	 
	 
			if (isRTCPeerConnection) {
				//set remote description
				peerConn.setRemoteDescription(new RTCSessionDescription(msg));
				//create answer
				console.log("Sending answer to peer.");
				peerConn.createAnswer(setLocalAndSendMessage, null, mediaConstraints);
			} else {
				//set remote description
				peerConn.setRemoteDescription(peerConn.SDP_OFFER, new SessionDescription(msg.sdp));
				//create answer
				var offer = peerConn.remoteDescription;
				var answer = peerConn.createAnswer(offer.toSdp(), mediaConstraints);
						console.log("Sending answer to peer.");
				setLocalAndSendMessage00(answer);
			}
		}
	} 
	else if (msg.type === 'answer' && started) {
		peerConn.setRemoteDescription(new RTCSessionDescription(msg));
	}
	else if (msg.type === 'candidate' && started) {
		var candidate = new RTCIceCandidate({sdpMLineIndex:msg.label, candidate:msg.candidate});
		peerConn.addIceCandidate(candidate);
	}
	else if (msg.type == 'chat'){
		if(chatNick.innerHTML == msg.toUser) {
			
			// Neu nhu partner dong cua so chat
			var  isActive = document.getElementById("CF"+msg.fromUser);
			if(isActive === null) {

				//Tao cua so chat moi
				createCF(msg.fromUser);
			} 
			addChatMsg(msg.fromUser, msg.fromUser, msg.color, msg.data);
		}
	}
	/*
	// entire message history
	else if (msg.type === 'history') { 	
		console.log("data : " +msg.data);
		console.log("data length: " +msg.data.length);

		if(msg.data != null) {
	        // insert every single message to the chat window
	        for (var i=0; i < msg.data.length; i++) {

	        	// Parse content of each json in history to json
				var json = JSON.parse(msg.data[i].content);			

				// Neu la tin nhan
				if(json.type == 'chat') {
	            addChatMsg(json.fromUser, 
	            			json.fromUser,
	            			json.color,
	            			json.data
	            			); //new Date(json.data[i].time)
				}
	        }
    	}
	} */
	else if (msg.type === 'bye' && started) {
		onRemoteHangUp();

		// Create chat frame
	} else if(msg.type === 'createCF') {
		
		if(chatNick.innerHTML === msg.toUser) {
			alert("receieve");
			createCF(msg.fromUser);
		}
	}
}
 
function processSignalingMessage00(message) {
	var msg = JSON.parse(message);
	 
	// if (msg.type === 'offer')--> will never happened since isRTCPeerConnection=true initially
	if (msg.type === 'answer' && started) {
		peerConn.setRemoteDescription(peerConn.SDP_ANSWER, new SessionDescription(msg.sdp));
	} 
	else if (msg.type === 'candidate' && started) {
		var candidate = new IceCandidate(msg.label, msg.candidate);
		peerConn.processIceMessage(candidate);
	} 
	else if (msg.type === 'bye' && started) {
		onRemoteHangUp();
	}
}
 
function setLocalAndSendMessage(sessionDescription) {
	peerConn.setLocalDescription(sessionDescription);
	sendMessage(sessionDescription);
}
 
function setLocalAndSendMessage00(answer) {
	peerConn.setLocalDescription(peerConn.SDP_ANSWER, answer);
	sendMessage({type: 'answer', sdp: answer.toSdp()});
	peerConn.startIce();
}
 
function onRemoteHangUp() {
	logg("Remote Hang up.");
	closeSession();
}
 
// Khi nhan nut Hang up
function onHangUp() {
	logg("Hang up.");
	//document.getElementById('anim').style.visibility='hidden';
	
	if (started) {
		sendMessage({type: 'bye'});
		closeSession();
	}
}
 
 // Ngat ket noi phien tro chuyen
function closeSession() {
	peerConn.close();
	peerConn = null;
	started = false;
	remotevid.src = "";	
}
 
window.onbeforeunload = function() {
	if (started) {
		sendMessage({type: 'bye'});
	}
}

// Su dung Webcam.
function startVideo() {

	navigator.getUserMedia = navigator.getUserMedia
							|| navigator.webkitGetUserMedia
							|| navigator.mozGetUserMedia;
	try {
		// Dung navigator.getUserMedia de yeu cau duoc su dung Webcam
		navigator.getUserMedia({audio: true, video: true}, successCallback, errorCallback);
	} catch (e) {
		navigator.getUserMedia("video, audio", successCallback, errorCallback);
	}
	
	function successCallback(stream) {
		// Dua video media stream vao viedeo tag
		sourcevid.src = window.webkitURL.createObjectURL(stream);
		//sourcevid.src = window.URL.createObjectURL(stream);		
		sourcevid.style.webkitTransform = "rotateY(180deg)";
		//sourcevid.style.mozTransform = "rotateY(180deg)";
		localStream = stream;
	}
	function errorCallback(error) {
		logg('An error occurred: [CODE ' + error.code + ']');
	}
}

// Ngung su dung Webcam.
function stopVideo() {
	sourcevid.src = "";
}

// Goi mesage len websocket.
function sendChatMsg(){

	// Lay noi dung
	chatInput = document.getElementById(to);

	//Khi nhan nut Enter (keyCode = 13)
	if(window.event.keyCode == 13){
		
		//Neu khong co noi dung
		if(chatInput.value.length < 1){
			return;
		}
		console.log("msg will be sent -> " + chatInput.value);
		// Them vao khung chat.
		addChatMsg("Me", to, "black", chatInput.value);

		// Goi message len websocket.
		sendMessage({
			type: "chat",
			fromUser: chatNick.innerHTML,
			toUser: to,
			data: chatInput.value,
			color: "red"
		});
		
		chatInput.value='';
	}
}

// send the message to websocket server
function sendMessage(message) {
	
	//Chuyen mesage sang kieu JSON
	var mymsg = JSON.stringify(message);
	logg("SEND: " + mymsg);
	//Goi message den websocket server.
	socket.send(mymsg);
}

// Them mesage vao khung chat.
function addChatMsg(fromUser, toUser, color, msg){

	console.log(fromUser+" "+toUser+" "+color+" "+msg);
	chatFrame = document.getElementById("CF" + toUser);
	console.log(chatFrame);
	var msgP = document.createElement("p");

	msgP.innerHTML = '<span style="color:'+color+'">'+fromUser+ ' : '+msg+'</span>'
	console.log(msgP.value);

	chatFrame.appendChild(msgP);
	console.log("Add thanh cong");
	//Tu dong cuon len
}

// Goi yeu cau tạo khung chat o ben kia
$('.sms').click(function () {

	// The name of your partner
	var to = $(this).parent().parent().find('.fname').html();

	console.log("msg will be sent to " + to);

	// Goi message len websocket.
	sendMessage({
		type: "createCF",
		fromUser: chatNick.innerHTML,
		toUser: to
	});

	sendMessage({
		type: "history"
	});
});

function createCF(to) {
	var isVisible = document.getElementById("CF" + to);

	if(isVisible == null) {
		$('.template').first().find('.to').html(to);
		$('.template').first().find('.mainCF').prop('id', "CF" +to);
		$('.template').first().find('.inputField').prop('id', to);
		$('.template').first().show();
		$('.template').first().removeClass('template');	
	} else {
		return false;
	}
}

// When an user connect to server, send a message
/*
function connect(nickname) {
	sendMessage({
		type: 'connection',
		nickname: nickname
	});
}*/
